package zhuhai.tedu.parttimess.controller;

import javax.servlet.http.HttpSession;


import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import zhuhai.tedu.parttimess.domain.Result;
import zhuhai.tedu.parttimess.exception.PasswordNotMatchException;
import zhuhai.tedu.parttimess.exception.ServiceException;
import zhuhai.tedu.parttimess.exception.UserNotFoundException;


/**
 * 当前项目中所有控制器类的基类
 */
public abstract class BaseController {
	
	/**
	 * 正确响应时的代号
	 */

	@ExceptionHandler(ServiceException.class)
	@ResponseBody
	public Result handleException(
			Exception e) {
		Integer state = null;
		
		if (e instanceof DuplicateKeyException) {
			// 400-违反了Unique约束的异常
			state = 400;
		} else if (e instanceof UserNotFoundException) {
			// 401-用户数据不存在
			state = 401;
		} else if (e instanceof PasswordNotMatchException) {
			// 402-密码错误
			state = 402;
		}
		return new Result(e.getMessage(),state);
	}
	
	/**
	 * 从Session中获取uid
	 * @param session HttpSession对象
	 * @return 当前登录的用户的id
	 */
	protected Integer getUidFromSession(HttpSession session) {
		return Integer.valueOf(
				session.getAttribute("uid").toString());
	}
	
}




